<template>
  <div id="tv_chart_container"></div>
</template>

<script>
import { userConfig } from '../config/userConfig';
import { DataPulseProvider } from './data-pulse-provider.js';
export default {
  name: 'TVChartContainer',
  props: {
    symbol: {
      type: String,
      required: true
    }
  },
  emits: ['symbolSaved'],
  data() {
    return {
      lastBar: null,
      subscriptions: new Map(),
      currentSymbol: null,
      subscribers: new Map(),
      watchListApi: null,
      watchlists: [],
      userId: userConfig.userId,// Default to 1 if not set
      symbolInfo: null // 添加全局 symbolInfo
    }
  },
  methods: {
    createCustomDatafeed(UDF_BASE_URL) {
      const defaultDatafeed = new Datafeeds.UDFCompatibleDatafeed(UDF_BASE_URL, 5000);
      const dataPulseProvider = new DataPulseProvider(defaultDatafeed._historyProvider, 10000);
      
      // 修改 subscribeBars 以保存 symbolInfo
      defaultDatafeed.subscribeBars = (symbolInfo, resolution, onRealtimeCallback, subscriberUID, onResetCacheNeededCallback) => {
        this.symbolInfo = symbolInfo; // 保存 symbolInfo
        return dataPulseProvider.subscribeBars(symbolInfo, resolution, onRealtimeCallback, subscriberUID, onResetCacheNeededCallback);
      };
      
      defaultDatafeed.unsubscribeBars = dataPulseProvider.unsubscribeBars.bind(dataPulseProvider);
      return defaultDatafeed;
    },

    unsubscribeKline(symbol, subscriberUID) {
      console.log(`[Unsubscribe] Attempting to unsubscribe ${symbol} for ${subscriberUID}`);
      
      if (symbol && this.subscriptions.has(symbol)) {
        const subscription = this.subscriptions.get(symbol);
        clearInterval(subscription.intervalId);
        this.subscriptions.delete(symbol);
        this.subscribers.delete(subscriberUID);
        
        if (symbol === this.currentSymbol) {
          this.currentSymbol = null;
          this.lastBar = null;
        }
        
        console.log(`[Unsubscribe] Successfully unsubscribed from ${symbol}`);
      }
    },
    setSymbol(newSymbol) {
      if (this.tvWidget) {
        this.tvWidget.setSymbol(newSymbol, '1D', () => {
          console.log('Symbol changed to:', newSymbol);
        });
      }
    },
    async initWatchListApi() {
      if(this.tvWidget) {
      const watchlist_api =  await this.tvWidget.watchList();

      // 监听列表删除事件
      watchlist_api.onListRemoved().subscribe(this, (watchId) => {
        console.log('[WatchListManager] List removed:', watchId);
        const watchMap = watchlist_api.getAllLists();
        console.log('[WatchListManager] List details:', watchMap);
        // 直接通过属性访问获取watchlist
        const list = watchMap[watchId];
        this.deleteWatchlist(list.title);  // 使用title作为name来删除
      });

      // 监听列表重命名事件
      watchlist_api.onListRenamed().subscribe(this, (watchId) => {
        console.log('[WatchListManager] List renamed:', watchId);
        const watchMap = watchlist_api.getAllLists();
        console.log('[WatchListManager] List details:', watchMap);
        const list = watchMap[watchId];
        const oldList = this.watchlists.find(l => l.id === list.id);
        if (oldList) {
          this.updateWatchlist({
            old_name: oldList.name,
            name: list.title
          });
          // 更新本地缓存
          oldList.name = list.title;
        }
      });
      }
    },


    // 加载自选列表
    async loadWatchlists() {
      try {
        const response = await fetch(`/api/watchlist/list?user_id=${this.userId}`);
        const result = await response.json();
        if (result.s === 'error') {
          console.error('[WatchListManager] Load failed:', result.errmsg);
          return;
        }

        // 获取 watchlist API
        const watchlist_api = await this.tvWidget.watchList();
        console.log('[WatchListManager] watchlist_api:', watchlist_api);
        // 添加所有列表到 TradingView
        for (const list of result.data) {
          // 打印list.items的内容，以及他是什么类型。items [],转成数组
          watchlist_api.createList(list.name,list.items);
        }
      } catch (error) {
        console.error('[WatchListManager] Load error:', error);
      }
    },

    // 保存自选列表
    async saveWatchlist(data) {
      try {
        const response = await fetch('/api/watchlist/save', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            user_id: this.userId,
            name: data.title,
            items: data.symbols || []
          })

        });
        const result = await response.json();
        if (result.s === 'error') {
          console.error('[WatchListManager] Save failed:', result.errmsg);
        }
      } catch (error) {
        console.error('[WatchListManager] Save error:', error);
      }
    },

    // 更新自选列表名称
    async updateWatchlist(data) {
      try {
        const response = await fetch('/api/watchlist/rename', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            user_id: this.userId,
            old_name: data.old_name,
            new_name: data.name
          })
        });
        const result = await response.json();
        if (result.s === 'error') {
          console.error('[WatchListManager] Update failed:', result.errmsg);
        }
      } catch (error) {
        console.error('[WatchListManager] Update error:', error);
      }
    },

    // 删除自选列表
    async deleteWatchlist(name) {
      try {
        const response = await fetch(`/api/watchlist/delete?user_id=${this.userId}&name=${encodeURIComponent(name)}`, {
          method: 'DELETE'
        });
        const result = await response.json();
        if (result.s === 'error') {
          console.error('[WatchListManager] Delete failed:', result.errmsg);
        }
      } catch (error) {
        console.error('[WatchListManager] Delete error:', error);
      }
    },
    
    async saveSymbol() {
      try {
        const response = await fetch(`/api/favorite/stocks`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            user_id: userConfig.userId,
            code: this.symbolInfo.ticker,
          })
        });
        if (response.ok) {
          this.$store.dispatch('updateWatchlist');
          console.log('Symbol saved successfully');
        } else {
          console.error('Failed to save symbol:', response.statusText);
        }
      } catch (error) {
        console.error('Error saving symbol:', error);
      }
    },
  },
  watch: {
    symbol: {
      handler(newSymbol) {
        console.log('[TVChartContainer] symbol prop changed to:', newSymbol)
        if (this.tvWidget) {
          console.log('[TVChartContainer] Attempting to set new symbol in chart')
          this.setSymbol(newSymbol)
        }
      },
      immediate: true
    }
  },
  mounted() {
    const UDF_BASE_URL = "http://localhost:5001/api";

    const widgetOptions = {
      width: "100%",
      height: "100%",
      symbol: this.symbol,
      interval: "D",
      timezone: "Asia/Shanghai",
      theme: "light",
      toolbar_bg: "#f1f3f6",
      container: "tv_chart_container",
      library_path: "/static/charting_library/",
      datafeed: this.createCustomDatafeed(UDF_BASE_URL + "/udf"),
      
      disabled_features: [
        "drawing_templates",
        "trading_account_manager"
        // "use_localstorage_for_settings",
      ],
      enabled_features: [
        "chart_template_storage",
        "hide_right_toolbar"
      ],
      custom_buttons: [{
        id: 'save_symbol',
        className: 'save-symbol-button',
        text: 'Save Symbol',
        onClick: () => this.saveSymbol()
      }],
      // widgetbar: {
      //   watchlist: false,
      //   watchlist_settings: {
      //       default_symbols: undefined
      //   },
      // },
      // settings_adapter: {
      //   initialSettings: {} ,
      //   setValue: function (key, value) {
      //       console.log(`set value: ${key} ${value}`);
      //       // savedwatch.c09gQLhCe444 {"symbols":[],"title":"Heel"}
      //       // 如果所示savedwatch 开头的key，就保存到后台
      //       // if (key.startsWith('savedwatch.')) {
      //       //     const data = JSON.parse(value);
      //       //     this.saveWatchlist(data);
      //       // }
      //   },
      //   removeValue: function (key) {
      //       console.log(`remove value: ${key}`);
      //   },
      // },
      
      charts_storage_url: UDF_BASE_URL,
      charts_storage_api_version: "1.1",
      client_id: "thingxs.com",
      user_id: "public_user_id",
      save_load: true,
      auto_save_delay: 5,
      load_last_chart: true,
    };

    this.tvWidget = new window.TradingView.widget(widgetOptions);
    
    this.tvWidget.onChartReady(() => {
      this.isChartReady = true;
      console.info(this.isChartReady)
      // Initialize watchlist API
      //this.initWatchListApi();

      // Load saved watchlists
      //this.loadWatchlists();

      console.log('TradingView chart is ready');

      this.tvWidget.headerReady().then(() => {
        const button = this.tvWidget.createButton();
        button.setAttribute('title', 'Click to save the current symbol');
        button.textContent = 'Save Symbol';
        button.addEventListener('click', () => {
          this.saveSymbol();
          alert("Symbol saved successfully!");
        });
      });
    });
  },
  beforeUnmount() {
    console.log('[Unmount] Cleaning up all subscriptions');
    for (const [symbol, subscription] of this.subscriptions.entries()) {
      this.unsubscribeKline(symbol, subscription.subscriberUID);
    }
    
    if (this.tvWidget) {
      this.tvWidget.remove();
      this.tvWidget = null;
    }
  }
}
</script>

<style scoped>
#tv_chart_container {
  height: 100%;
}
</style>
